﻿using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Read.Apilication.Common.MenuRole;
using B.S.BasicData.Read.DTOS;
using MediatR;

namespace B.S.BasicData.Read.Apilication.Handler.MenuRole
{
    public class GetRoleMenuCommandHandle:IRequestHandler<GetRoleMenuCommand,ApiResult<List<RolePremissDTO>>>
    {
        private readonly IBaseRepository<MenuRoleModel> MeunRoleDal;


        private readonly IBaseRepository<MenuModel> MenuDal;
        public GetRoleMenuCommandHandle(IBaseRepository<MenuRoleModel> meunRoleDal, IBaseRepository<MenuModel> menuDal)
        {
            MeunRoleDal = meunRoleDal;
            MenuDal = menuDal;
        }

        public Task<ApiResult<List<RolePremissDTO>>> Handle(GetRoleMenuCommand request, CancellationToken cancellationToken)
        {
            var list = request.Rle.Split(',').ToList();
            var rolemenuQuery = MeunRoleDal.GetAll();
            List<int> model = new List<int>();
            foreach (var item in list)
            {
                var mIds = rolemenuQuery.Where(x => x.RoleId == Convert.ToInt32(item)).Select(x => x.MenuId).ToList();
                model.AddRange(mIds);
            }     
            var menuQuery = MenuDal.GetAll().Where(x => !x.IsDeleted);
            var data = Find(0, menuQuery.ToList(), model);

            ApiResult<List<RolePremissDTO>> result = new ApiResult<List<RolePremissDTO>>()
            {
                Code = ApiEnum.Success,
                Message = "成功",
                Data = data
            };
            return Task.FromResult(result);
        }

        /// <summary>
        /// 构建菜单树 生成包含子菜单的层级结构
        /// </summary>
        /// <param name="id">当前父级菜单id</param>
        /// <param name="ids">所有菜单列表</param>
        /// <param name="mid">目前角色所拥有的菜单ID</param>
        /// <returns></returns>
        private List<RolePremissDTO> Find(int id, List<MenuModel> ids, List<int> mid)
        {
            var res = ids.Where(x => x.ParentId == id && mid.Contains(x.MenuId)).ToList();

            List<RolePremissDTO> menus = new List<RolePremissDTO>();
            foreach (var item in res)
            {
                menus.Add(new RolePremissDTO
                {
                    MenuUrl = item.MenuUrl,
                    MenuName = item.MenuName,
                    Childer = Find(item.MenuId,ids,mid)

                });
            }

            return menus;
        }


    }
}
